package com.didi.gulimall.auth.controller;

import com.didi.gulimall.auth.service.AuthMemberService;
import com.didi.gulimall.auth.vo.UserLoginVo;
import com.didi.gulimall.auth.vo.UserRegistVo;
import com.didi.gulimall.common.constant.AuthServerConstant;
import com.didi.gulimall.common.constant.SystemConstant;
import com.didi.gulimall.common.to.MemberResponseVo;
import com.didi.gulimall.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 10626
 */
@Api("认证-用户接口")
@Slf4j
@RequestMapping("auth/member")
@Controller
public class MemberController {
    @Autowired
    private AuthMemberService authMemberService;

    @Value("${gulimall.reg}")
    private String regHtml;


    @ResponseBody
    @ApiOperation("发送验证码")
    @GetMapping("sendcode")
    public R sendCode(
            @ApiParam(name = "phone", value = "手机号", required = true)
            @RequestParam("phone") String phone) {
        return authMemberService.sendCode(phone);
    }

    @ApiOperation("登录")
    @PostMapping("login")
    public String login(
            @ApiParam(name = "userLoginVo", value = "用户登录Vo", required = true)
            @Valid UserLoginVo userLoginVo,
            RedirectAttributes redirectAttributes,
            HttpSession session) {
        return authMemberService.login(userLoginVo, redirectAttributes, session);
    }

    @ApiOperation("注册会员")
    @PostMapping("regist")
    public String registered(
            @ApiParam(name = "userRegistVo", value = "会员注册VO", required = true)
            @Valid UserRegistVo userRegistVo,
            BindingResult bindingResult,
            RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            bindingResult.getFieldErrors().forEach((fieldError) -> {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            });
            redirectAttributes.addFlashAttribute(SystemConstant.ERRORS, map);
            return "redirect:" + regHtml;
        }
        return authMemberService.registered(userRegistVo, redirectAttributes);
    }
}
